<script>
import { memberBindWechat, updateProfile, uploadImg } from '@/api/user'

export default {
  data() {
    return {
      memberModel: {
        memberInfo: { nickname: '', avatar: '' },
      },
      rules: {
        'memberInfo.nickname': {
          type: 'string',
          required: true,
          message: '请填写昵称',
          trigger: ['blur', 'change'],
        },
      },
      fileListData: [],
    }
  },
  computed: {},
  created() {
    this.memberModel.memberInfo.nickname = this.$store.user.userInfo.nickname
    this.memberModel.memberInfo.avatar = this.$store.user.userInfo.avatar
    if (this.memberModel.memberInfo.avatar != '') {
      this.fileListData.push({ url: this.memberModel.memberInfo.avatar })
    }
  },
  methods: {
    async submit() {
      const res = await updateProfile(this.memberModel.memberInfo)
      if (res.ok) {
        this.$toast('修改成功')
      }
    },
    async bindWeChat() {
      uni.login({
        provider: 'weixin',
        async success(loginResp) {
          // 登录成功
          if (loginResp.errMsg == 'login:ok') {
            await memberBindWechat({ code: loginResp.code })
          }
        },
        fail(err) {
        // 登录授权失败
        // err.code是错误码
          console.log(err)
          this.$toast('登录失败')
        },
      })
    },
    async afterRead(event) {
      const result = await uploadImg(event.file.url)
      const data = JSON.parse(result)
      if (data.code === 0) {
        this.memberModel.memberInfo.avatar = data.data.url
        this.fileListData[0].url = data.data.url
        this.$store.user.setAvatar(data.data.url)
      }
    },
  },
}
</script>

<template>
  <view class="w-full">
    <uni-card>
      <u-form
        ref="uForm"
        label-position="left"
        :model="memberModel"
        :rules="rules"
        style="font-size: large;"
      >
        <u-form-item
          label="昵称"
          prop="memberInfo.nickname"
          border-bottom
        >
          <u--input
            v-model="memberModel.memberInfo.nickname"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item
          label="头像"
          prop="memberInfo.avatar"
          border-bottom
        >
          <u-upload
            v-model:file-list="fileListData"
            name="file"
            :multiple="false"
            :preview-full-image="true"
            @after-read="afterRead"
          ></u-upload>
        </u-form-item>
        <u-button type="success" @click="submit">
          提交
        </u-button>
      </u-form>
    </uni-card>
    <uni-card>
      <u-button type="primary" @click="bindWeChat">
        绑定微信
      </u-button>
    </uni-card>
  </view>
</template>

<style></style>
